//
//  EFADeviceMapVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/12.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADeviceMapVC.h"
#import <MAMapKit/MAMapKit.h>
#import <MapKit/MapKit.h>
#import "EFADevMapTCell.h"
#import "EFAModel.h"
#import "EFAAnnotationView.h"
#import "EFADeviceInfoVC.h"

@interface EFADeviceMapVC ()<UITableViewDelegate, UITableViewDataSource, MAMapViewDelegate, EFAAnnotationViewDelegate, EFADevMapTCellDelegate>

@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray<MAPointAnnotation *> *annotations;
@property(strong,nonatomic)NSArray<UIImage *> *markerIconArray;
@property(strong,nonatomic)NSArray<UIImage *> *chooseMarkerIconArray;
@end

static NSString *const kReuseCellId = @"EFADevMapTCell";

@implementation EFADeviceMapVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    // 地图显示定位
////    [self.mapView showAnnotations:self.annotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
//}

- (void)initNavigationBar {
    self.navigationItem.title = @"设备分布";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    //marker图标
    _markerIconArray = [[NSArray alloc]initWithObjects:
                        [UIImage imageNamed:@"icon_dev_lixian"],
                        [UIImage imageNamed:@"icon_map_address_red"],
                        [UIImage imageNamed:@"icon_map_address_yellow"],
                        [UIImage imageNamed:@"icon_dev_guzhang"],
                        [UIImage imageNamed:@"icon_map_address_green"],nil];
    //选中marker图标
    _chooseMarkerIconArray = [[NSArray alloc]initWithObjects:
                             [UIImage imageNamed:@"icon_dev_lixian_big"],
                             [UIImage imageNamed:@"icon_map_address_red_big"],
                             [UIImage imageNamed:@"icon_map_address_yellow_big"],
                             [UIImage imageNamed:@"icon_dev_guzhang_big"],
                             [UIImage imageNamed:@"icon_map_address_green_big"],nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.emptyDataSetDelegate = self;
//    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    //    [self.tableView.mj_header beginRefreshing];
    
    // 地图增加定位
    self.mapView.delegate = self;
    [self.mapView addAnnotations:self.annotations];
    [self.mapView showAnnotations:self.annotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有设备" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.device_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFADevMapTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.device_list.count) {
        [cell configViewWithEFADeviceListItem:self.device_list[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.annotations.count) {
        [self.mapView selectAnnotation:self.annotations[indexPath.row] animated:NO];
        [self.mapView showAnnotations:@[self.annotations[indexPath.row]] edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
    }
}

#pragma mark - MAMapViewDelegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        EFAAnnotationView *annotationView = (EFAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[EFAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            annotationView.delegate = self;
            annotationView.centerOffset = CGPointMake(0, -18);
        }
        NSUInteger index = [self.annotations indexOfObject:annotation];
        if (index != NSNotFound && index < self.device_list.count) {
            DeviceListItem *item = self.device_list[index];
//            NSString *imgName = [[EFADeviceProtocolModel sharedInstance] threeStateMapImgNameWithSt:item.efairydevice_alarm_id];
            switch (item.efairydevice_alarm_id) {
                case 0:
                    annotationView.image = _markerIconArray[0];
                    break;
                case 1:
                     annotationView.image = _markerIconArray[1];
                    break;
                case 2:
                     annotationView.image = _markerIconArray[2];
                    break;
                case 3:
                     annotationView.image = _markerIconArray[3];
                    break;
                case 6:
                     annotationView.image = _markerIconArray[4];
                    break;
                default:
                    break;
            }
           
        }
//        annotationView.canShowCallout = YES;       //设置气泡可以弹出，默认为NO
//        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
//        annotationView.draggable = NO;            //设置标注可以拖动，默认为NO
        return annotationView;
    }
    return nil;
}
// 这里的气泡只有原生的才会触发该回调
- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
    ;
}

//取消点击
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view{
    if([view.image isEqual:_chooseMarkerIconArray[0]]){
        view.image =_markerIconArray[0];
    }else if([view.image isEqual:_chooseMarkerIconArray[1]]){
        view.image =_markerIconArray[1];
    }else if([view.image isEqual:_chooseMarkerIconArray[2]]){
        view.image =_markerIconArray[2];
    }else if([view.image isEqual:_chooseMarkerIconArray[3]]){
        view.image =_markerIconArray[3];
    }else if([view.image isEqual:_chooseMarkerIconArray[4]]){
        view.image =_markerIconArray[4];
    }
}

//marker被点击
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    if([view.image isEqual:_markerIconArray[0]]){
        view.image =_chooseMarkerIconArray[0];
    }else if([view.image isEqual:_markerIconArray[1]]){
         view.image =_chooseMarkerIconArray[1];
    }else if([view.image isEqual:_markerIconArray[2]]){
         view.image =_chooseMarkerIconArray[2];
    }else if([view.image isEqual:_markerIconArray[3]]){
         view.image =_chooseMarkerIconArray[3];
    }else if([view.image isEqual:_markerIconArray[4]]){
         view.image =_chooseMarkerIconArray[4];
    }
}

#pragma mrak - EFAAnnotationViewDelegate
- (void)tappedForAnnotationView:(EFAAnnotationView *)annotationView {
    NSUInteger index = [self.annotations indexOfObject:annotationView.annotation];
    if (index != NSNotFound && index < self.device_list.count) {
        [self jumpToDeviceInfoWithDeviceListItem:self.device_list[index]];
    }
    NSLog(@"点击的index = %ld", (unsigned long)index);
    NSLog(@"点击气泡:%@", annotationView.annotation.title);
}
- (void)annotationView:(EFAAnnotationView *)annotationView naviTapped:(UIView *)naviView {
    NSUInteger index = [self.annotations indexOfObject:annotationView.annotation];
    if (index != NSNotFound && index < self.device_list.count) {
        [self jumpToSelMapWithDeviceListItem:self.device_list[index]];
    }
}

#pragma mark - EFADevMapTCellDelegate
- (void)devMapTCell:(EFADevMapTCell *)cell naviBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row < self.device_list.count) {
        [self jumpToSelMapWithDeviceListItem:self.device_list[indexPath.row]];
    }
}

#pragma mark - event response
#pragma mark - private methods
- (void)jumpToDeviceInfoWithDeviceListItem:(DeviceListItem *)item {
    EFADeviceInfoVC *vc = [[EFADeviceInfoVC alloc] init];
    vc.deviceId = item.efairydevice_id;
    [self showViewController:vc sender:nil];
}
- (void)jumpToSelMapWithDeviceListItem:(DeviceListItem *)item {
    BOOL baiduMap = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]];
    BOOL gaodeMap = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]];
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请选择地图" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"用iPhone自带地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self jumpToAppleMapWithDeviceListItem:item];
    }]];
    if (baiduMap) {
        [alertVC addAction:[UIAlertAction actionWithTitle:@"用百度地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self jumpToBaiduMapWithDeviceListItem:item];
        }]];
    }
    if (gaodeMap) {
        [alertVC addAction:[UIAlertAction actionWithTitle:@"用高德地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self jumpToGaodeMapWithDeviceListItem:item];
        }]];
    }
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)jumpToAppleMapWithDeviceListItem:(DeviceListItem *)item {
    //使用自带地图导航
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(item.efairydevice_location_lat, item.efairydevice_location_lng) addressDictionary:nil]];
    toLocation.name = item.efairydevice_name;
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                   MKLaunchOptionsShowsTrafficKey:@(YES)}];
}
- (void)jumpToBaiduMapWithDeviceListItem:(DeviceListItem *)item {
//    NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:%@&mode=driving&src=webapp.navi.juliai.efairy", self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, item.efairydevice_location_lat, item.efairydevice_location_lng, item.efairydevice_name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:%@&mode=driving&src=webapp.navi.juliai.efairy", self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, item.efairydevice_location_lat, item.efairydevice_location_lng, item.efairydevice_name] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self callOpenURL:[NSURL URLWithString:urlString]];
}
- (void)jumpToGaodeMapWithDeviceListItem:(DeviceListItem *)item {
    NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=电次元&backScheme=efairy&sid=BGVIS1&did=BGVIS2&dlat=%f&dlon=%f&dname=%@&dev=0&t=0", item.efairydevice_location_lat, item.efairydevice_location_lng, item.efairydevice_name] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self callOpenURL:[NSURL URLWithString:urlString]];
}
- (void)callOpenURL:(NSURL *)url {
    if ([[UIDevice currentDevice].systemVersion integerValue] >= 10) { //iOS10以后,使用新API
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            NSLog(@"scheme调用结束");
        }];
    } else { //iOS10以前,使用旧API
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    [self.tableView reloadData];
}

//- (void)tableViewEndRefresh:(BOOL)isHeader {
//    NSLog(@"停止刷新是否是头部---%zd", isHeader);
//    if (isHeader) {
//        [self.tableView.mj_header endRefreshing];
//    } else {
//        [self.tableView.mj_footer endRefreshing];
//    }
//}
//
//- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    //    [self requestUserListWithHeader:isHeader];
//}
#pragma mark - network request
- (void)requestUserListWithHeader:(BOOL)isHeader {
    //    // 发布Cos需要登录
    //    if (![KABModel sharedInstance].isLogin) {
    //        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
    //        [self tableViewEndRefresh:isHeader];
    //        return;
    //    }
    //
    //    NSInteger startIndex = isHeader ? 0 : self.userList.user_list.count;
    //    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
    //                           @"visitor_id" : @([KABModel sharedInstance].userInfo.uid),
    //                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
    //                           @"index" : @(startIndex),
    //                           @"size" : @(kRequestUserSize)};
    //    NSLog(@"请求粉丝、爱豆的参数：%@", pars);
    //    NSString *urlStr = (self.viewType == KABMineUserListVCTypeFollow) ? [ApiManager apiMineFollow] : [ApiManager apiMineFan];
    //    [[XDAFNetworking sharedInstance] GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //        NSLog(@"请求粉丝、爱豆返回：%@", responseObject);
    //        [self tableViewEndRefresh:isHeader];
    //        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
    //            [self userListWithDictionary:responseObject isAddMore:!isHeader];
    //        } else {
    //            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
    //        }
    //        [self refreshWholeView];
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //        NSLog(@"请求粉丝、爱豆失败：%@", error);
    //        [self tableViewEndRefresh:isHeader];
    //        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    //    }];
}

#pragma mark - getters and setters
//- (MJRefreshNormalHeader *)mj_header {
//    if (!_mj_header) {
//        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
//        _mj_header.lastUpdatedTimeLabel.hidden = YES;
//    }
//    return _mj_header;
//}

- (NSMutableArray *)annotations {
    if (!_annotations) {
//        _annotations = [NSMutableArray arrayWithCapacity:self.deviceModel.device_list.count];
//        for (EFADeviceListItem *item in self.deviceModel.device_list) {
//            MAPointAnnotation *anno = [[MAPointAnnotation alloc] init];
//            anno.title = item.efairydevice_name;
//            anno.subtitle = item.map_state_str;
//            CLLocationCoordinate2D location = {item.efairydevice_location_lat, item.efairydevice_location_lng};
//            anno.coordinate = location;
//            [_annotations addObject:anno];
//        }
        _annotations = [NSMutableArray arrayWithCapacity:self.device_list.count];
        for (DeviceListItem *item in self.device_list) {
            MAPointAnnotation *anno = [[MAPointAnnotation alloc] init];
            anno.title = item.efairydevice_name;
            anno.subtitle = item.map_state_str;
            CLLocationCoordinate2D location = {item.efairydevice_location_lat, item.efairydevice_location_lng};
            anno.coordinate = location;
            [_annotations addObject:anno];
        }
    }
    return _annotations;
}

@end
